import React from 'react'
import BaseComponent from 'basecomponent'
import icons from 'icons'
import Button from "button";
import './style.scss'
import {Cascader} from 'antd';
import AntTable from 'anttable'
import store from 'store'
import api from 'apis'
import {grideType, gradeType} from 'utils/staticType'
import moment from 'moment'
import UploadMusicModal from 'uploadMusicModal'
import appConfig from 'config'
import auth from 'auth'

const typeName = ['FirstTag','SecondTag','ThirdTag'];
class Major extends BaseComponent {
  constructor() {
    super(...arguments);
    const location = this.props.location;
    // console.log('state', location.state)
    this.state = {
      majorData: {
        Name: '',
        Image: '',
        CommonMajor: {Id: -1},
        Institute: {Id: location.state ? location.state.cid : -1},
        College: {Id: location.state ? location.state.uid : -1},
        Introduce: '',
        Grade: {},
        Timestamp: 0,
        Music: {},
      },
      from: location.state? location.state.from : '',
      placeHolder:'',
      bachelorData:[], //本科
      juniorData:[], //专科
      masterData:[], //硕士
      category: location.state ? location.state.category : -1,
      musicData: [{
        Id: '-',
        Name: '添加',
        PlayTimes:'-',
        Duration:'-',
        updateTime:'-'
      }],
      showModal:false,
    }
    store.set('CurrentMId', location.query.Id ? location.query.Id : 1)
  }

  componentDidMount() {
    const {majorData} = this.state
    this.setState({from: this.props.location.state? this.props.location.state.from : ''})
    if (!(majorData.Id === -1 || typeof majorData.Id === 'undefined')) {
      this.getMajorDetail(majorData.Id)
    }
    this.getMajorDictList(grideType.bachelor,true)
    this.getMajorDictList(grideType.junior,true)
    this.getMajorDictList(grideType.master,true)
  }

  getMajorDetail(mid) {
    const{musicData}=this.state
    let id = mid ? mid : store.get('CurrentMId');
    this.MDetailRP && this.MDetailRP.request.abort();
    this.MDetailRP = api.university.getMajorDetail(id);
    this.registerRequest(this.MDetailRP.request);
    this.MDetailRP.promise
      .then((res) => {
        let data = res.Data || []
        let holderName = ''
        if(data.CommonMajor){
          holderName = `${data.CommonMajor.FirstTag} / ${data.CommonMajor.SecondTag} / ${data.CommonMajor.ThirdTag}`
        }
        if(data.Music){
          musicData[0] = data.Music
        }
        this.setState({majorData: data, placeHolder: holderName , musicData:musicData});
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  handleSubmit() {
    const {majorData} = this.state;
    if (!(majorData.Id === -1 || typeof majorData.Id === 'undefined')) {
      this.reviseMajorRP && this.reviseMajorRP.request.abort();
      this.reviseMajorRP = api.university.reviseMajor(majorData.Id, majorData);
      this.registerRequest(this.reviseMajorRP.request);
      this.reviseMajorRP.promise
        .then((res) => {
          res.Data && this.setState({majorData: res.Data},this.getMajorDetail(res.Data.Id));
          alert('修改成功')
        })
        .catch((err) => {
          alert(err.msg)
        })
    } else {
      this.addMajorRP && this.addMajorRP.request.abort();
      this.addMajorRP = api.university.addMajor(majorData);
      this.registerRequest(this.addMajorRP.request);
      this.addMajorRP.promise
        .then((res) => {
          res.Data && this.setState({majorData: res.Data},this.getMajorDetail(res.Data.Id));
          alert('添加成功')
        })
        .catch((err) => {
          alert(err.msg)
        })
    }
  }

  getMajorDictList(parent,init,targetParent,targetOption){
    const {bachelorData,juniorData,masterData} =this.state
    if(!init){this.majorDListRP.request.abort()}
    this.majorDListRP = api.majordict.getMajorDictList(parent);
    this.registerRequest(this.majorDListRP.request);
    this.majorDListRP.promise
      .then((res)=>{
        let data = res.Data || [];
        if(init){
          let optionData = data.map(function (item) {
            return {
              value:item.Id,
              label:item.FirstTag,
              origin:item,
              isLeaf: false,
            }
          })
          if(parent === grideType.bachelor){ //本科
            this.setState({bachelorData:optionData})
          }
          if(parent === grideType.junior){ //专科
            this.setState({juniorData:optionData})
          }
          if(parent === grideType.master){ // 硕士
            this.setState({masterData:optionData})
          }
        } else {
          if(targetOption){
            let optionData = data.map(function (item) {
              return {
                value:item.Id.toString(),
                label:item[typeName[item.Type - 1]],
                origin:item,
                isLeaf: item.Type === typeName.length,
              }
            })
            targetOption.children = optionData
            if(targetParent === grideType.bachelor){
              this.setState({bachelorData:[...bachelorData]})
            }
            if(targetParent === grideType.junior){ //专科
              this.setState({juniorData:[...juniorData]})
            }
            if(targetParent === grideType.master){ // 硕士
              this.setState({masterData:[...masterData]})
            }
          }
        }
      })
      .catch((err)=>{
        alert(err.msg)
      })
  }

  handleLoadData(parent,selectedOptions){
    const targetOption = selectedOptions[selectedOptions.length - 1];
    this.getMajorDictList(targetOption.value,false,parent,targetOption)
  }

  onChange(value, selectedOptions){
    const {majorData} = this.state
    if(selectedOptions && selectedOptions.length >= 1){
      majorData.CommonMajor.Id = selectedOptions[selectedOptions.length-1].origin.Id
      this.setState({
        majorData: majorData
      })
    }
  }

  handleMusicView(musicView) {
    const {musicData,majorData} = this.state
/*    if (majorData.CommonMajor) {
      delete majorData.CommonMajor
    }*/
    musicData[0].Id = musicView.Id
    musicData[0].Name = musicView.Name
    musicData[0].updateTime = moment(new Date()).format('YYYY.MM.DD hh:mm')
    let reviseMajor = Object.assign({},majorData,{Music:{Id:musicView.Id}})
    this.setState({musicData: musicData})
    this.RMajorRp && this.RMajorRp.request.abort();
    this.RMajorRp = api.university.reviseMajor(majorData.Id , reviseMajor);
    this.registerRequest(this.RMajorRp.request);
    this.RMajorRp.promise
      .then((res) => {
        res.Data&&this.setState({majorData:res.Data},this.getMajorDetail(res.Data.Id))
      })
      .catch((err)=>{
        alert(err.msg)
      })
  }

  render() {
    const {majorData,from,bachelorData,juniorData,masterData,musicData,placeHolder,showModal} = this.state
    const voiceColumns = [{
      title: '编号',
      dataIndex: 'Id',
      key: 'Id',
    }, {
      title: '专业名称',
      dataIndex: 'Name',
      key: 'Name',
    }, {
      title: '播放量',
      dataIndex: 'PlayTimes',
      key: 'PlayTimes',
    }, {
      title: '时长',
      dataIndex: 'Duration',
      key: 'Duration',
    }, {
      title: '上传时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
             <a onClick={() => {
               if(!majorData.Id || majorData.Id === -1){
                 alert('请先添加专业')
               }else {
                 this.setState({showModal:true})
               }
             }}>上传</a>
            <span className="ant-divider"/>

          <a href={`${appConfig.apiHost}/File/?pid=${text.Url}&key=${auth.getFileToken()}`}
             download={`${text.Name}.mp3`}>
            下载
          </a>
              <span className="ant-divider"/>
          <a onClick={() => {
          }}>删除</a>
        </span>
        ),
      }
    ];
    const voiceRowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
      }),
    };
    return (
      <div className={'sem-main-content'}>
        <div className={'major-button-wrapper'}>
          <Button className={'back-button'} onClick={() => {
            if(from === '' || typeof from === 'undefined'){
              this.props.router.replace({pathname:'/home/add/college',query:{Id:-1} })
            }else{
              this.props.router.goBack()
            }
          }}>{Button.AddOn({
            src: icons.backIcon, style: {
              width: '1rem',
              height: '1rem',
              display: 'block',
              backgroundRepeat: 'no-repeat',
            }
          })}</Button>
          <div className={'add-name'}>
            添加专业
          </div>
          <Button className={'save-btn'} onClick={this.handleSubmit.bind(this)}>保存</Button>
        </div>
        <div className={'major-top-div'}>
          <div className={'option-wrapper'}>
            <div className={'option-title'}>专业名称</div>
            <input className={'option-input'} type={'text'} value={majorData.Name}
                   onChange={(e) => {
                     this.setState({majorData: Object.assign(majorData, {Name: e.target.value})})
                   }}
            />
          </div>
        </div>

          <div className={'add-select-div'}>
            <Cascader className={'level-select '}
                      size={'large'}
                      options={bachelorData}
                      loadData={this.handleLoadData.bind(this,grideType.bachelor)}
                      onChange={this.onChange.bind(this)}
                      placeholder={majorData.CommonMajor ? (majorData.CommonMajor.Grade === gradeType.benke ? placeHolder : '本科专业'):'本科专业'}
                      notFoundContent={'-'}>
            </Cascader>
            <Cascader className={'batch-select'}
                      size={'large'}
                      options={juniorData}
                      loadData={this.handleLoadData.bind(this,grideType.junior)}
                      onChange={this.onChange.bind(this)}
                      placeholder={majorData.CommonMajor ? (majorData.CommonMajor.Grade === gradeType.zhuanke ? placeHolder : '专科专业'):'专科专业'}
                      notFoundContent={'-'}>
            </Cascader>
            <Cascader className={'category-select'}
                      options={masterData}
                      loadData={this.handleLoadData.bind(this,grideType.master)}
                      onChange={this.onChange.bind(this)}
                      size={'large'}
                      placeholder={majorData.CommonMajor ? (majorData.CommonMajor.Grade === gradeType.shuoshi ? placeHolder : '硕士专业'):'硕士专业'}
                      notFoundContent={'-'}>
            </Cascader>
          </div>

        <div className={'major-middle-div'}>
          <div className={'title-wrapper'}>
            <span className={'title-bar'}/>
            <span className={'title-text'}>专业简介</span>
{/*            <Button className={'title-btn-save'} buttonType={'button'} onClick={() => {
            }}>保存</Button>*/}
          </div>
          <textarea className={'work-intro'} value={majorData.Introduce}
                    onChange={(e) => {
                      this.setState({majorData: Object.assign(majorData,{Introduce: e.target.value})})
                    }}/>
        </div>

        <div className={'major-middle-div voice'}>
          <div className={'title-wrapper'}>
            <span className={'title-bar'}/>
            <span className={'title-text'}>专业视频</span>
          </div>
          <AntTable columns={voiceColumns} data={musicData} rowSelection={voiceRowSelection} pagenation={false}/>
        </div>
        {showModal && <UploadMusicModal handleSave={(musicView)=>{this.handleMusicView(musicView)}}
                                        hideModal={()=>{this.setState({showModal:false})}}/>}
      </div>
    );
  }
}

module.exports = Major;
